<?php if ( ! defined('BASEPATH')) exit('This file does not run directly. Sorry.'); ?>
<?php
/**
 * Kalaisoo.
 *
 * A lightweight no-framework framework written in PHP.
 *
 * @package Kalaisoo
 * @author $Author: info@sah-company.com $
 * @version $Id: attach.php 127 2012-01-12 01:46:11Z info@sah-company.com $
 */

/**
 * Kalaisoo Attach Plugin Class.
 *
 * @package Kalaisoo
 * @subpackage Plugin
 * @author $Author: info@sah-company.com $
 */
class Attach_Plugin extends Plugin
{
	/**
	 * holds the input
	 *
	 * @var Input
	 */
	protected $input;

	/**
	 * constructs a new attach plugin.
	 */
	public function __construct()
	{
		parent::__construct();
		$this->init();
	}
	
	/**
	 * initializes the attach plugin.
	 */
	protected function init()
	{
		$this->registry->loader->lib(array('redbean', 'gestalt'));
		$this->registry->loader->helper(array('url', 'textile'));
		$this->input = new Input();
	}
	
	/**
	 * adds a new subform depending on type, id and path. The path is given as get parameter
	 *
	 * @param string $type
	 * @param mixed $id
	 */
	public function execute($type, $id)
	{
		$path = explode('/', $this->input->path);
		$tail = array_pop($path); // get rid of the last slash
		$id_to_attach = array_pop($path);
		$model_to_attach = array_pop($path);
		if (strpos($model_to_attach,'own')===0) {
			$list_type = 'own';
			$actual_model = substr($model_to_attach, 3);
		} elseif (strpos($model_to_attach,'shared')===0) {
			$list_type = 'shared';
			$actual_model = substr($model_to_attach, 6);
		} else {
			// this should never occur?!
			$list_type = 'unknown';
			$actual_model = $model_to_attach;
		}
		$actual_model = strtolower($actual_model);
		$newpath = $type;
		while ($part = array_shift($path)) {
			$id = array_shift($path);
			$newpath .= '['.$part.']['.$id.']';
		}
		$this->loadEnvironment($type, $id);
		$featureName = 'Feature'.ucfirst($list_type);
		$gestalt = new Gestalt($this->record);
		$gestalt->fn = $newpath.'['.$list_type.ucfirst($actual_model).']';
		$feature = new $featureName($gestalt);
		$bean = R::dispense($actual_model);
		$m = time()+rand(1, 1000); // make nearly certainly a unique key in this area
		echo $feature->subGestalt($bean, $m, $this->record, $newpath);
	}
	
	/**
	 * loads the beans model file and returns true.
	 *
	 * Load or dispense a bean of $type. When $id is not 0 (zero) then the bean will be
	 * loaded otherwise it will be dispensed.
	 * The bean is pushed to our view data.
	 *
	 * @param string $type
	 * @param mixed $id
	 * @return bool
	 */
	protected function loadEnvironment($type, $id = 0)
	{
		// load the model and its language file
		$this->registry->loader->model($type, $load_language = true);
		// dispense or load a bean and give it to view
		if ( ! $id) {
			$this->record = R::dispense($type);
		} else {
			$this->record = R::load($type, $id);
		}
		return true;
	}
}